package com.love.marriage.cloud.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.love.marriage.cloud.service.TencentDtService;
import com.love.marriage.common.redisKey.IpKey;
import com.love.marriage.config.WeChatDtConfig;
import com.love.marriage.regionInfo.service.RegionInfoService;
import com.love.marriage.regionInfo.vo.RegionDetailInfoVo;
import com.love.marriage.utils.IpUtils;
import com.love.marriage.utils.RedisUtils;
import com.love.marriage.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
@Slf4j
public class TencentDtServiceImpl implements TencentDtService {

    private final WeChatDtConfig weChatDtConfig;

    private final RegionInfoService regionInfoService;

    private final RedisUtils redisUtils;

    @Override
    public Map<String, Object> ip2address(HttpServletRequest request, String ip) throws Exception {
        if (ip == null || ip.isEmpty()) {
            ip = IpUtils.getIpAddr(request);
            log.info("ip为空，使用本机ip:{}", ip);
        }
        String ipInfo = redisUtils.get(IpKey.ipKey.getPrefix() + ":" + ip);
        if (StringUtils.isNotBlank(ipInfo)) {
            log.info("redis ip缓存：{}", ipInfo);
            return JSONObject.parseObject(ipInfo, Map.class);
        }
        StringBuilder urlStr = new StringBuilder(weChatDtConfig.getUrl());
        urlStr.append("?key=").append(weChatDtConfig.getKey());
        if (ip != null && !ip.isEmpty()) {
            urlStr.append("&ip=").append(ip);
        }
        BufferedReader reader = null;
        JSONObject map;
        try {
            URL url = new URL(urlStr.toString());
            reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            log.info("通过腾讯地图获取ip信息结果:{}", response);
            map = JSONObject.parseObject(response.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        // Retrieve ad_info map and validate
        JSONObject result = (JSONObject) map.get("result");
        JSONObject adInfo = (JSONObject) result.get("ad_info");
        if (adInfo == null) {
            log.warn("ad_info is missing in the response");
            throw new Exception("ad_info is missing in the response");
        }
        // Extract province, city, and district with null safety
        String province = (String) adInfo.getOrDefault("province", "");
        String city = (String) adInfo.getOrDefault("city", "");
        String district = (String) adInfo.getOrDefault("district", "");
        Map<String, Object> res = new HashMap<>();
        // Populate response map
        res.put("province", province);
        res.put("city", city);
        res.put("district", district);
        // Get detailed region info
        RegionDetailInfoVo regionDetailInfoVo = regionInfoService.reginDetailInfo(province, city, district);
        if (regionDetailInfoVo != null) {
            res.put("districtId", regionDetailInfoVo.getDistrictId());
            res.put("cityId", regionDetailInfoVo.getCityId());
            res.put("provinceId", regionDetailInfoVo.getProvinceId());
        }
        redisUtils.setEx(IpKey.ipKey, ip, JSONObject.toJSONString(res), 60 * 60 * 24 * 7, TimeUnit.SECONDS);
        return res;
    }
}
